package com.xgc.erp.info.entity.service;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;
import com.xgc.common.base.service.BaseService;
import com.xgc.common.model.Entity;
import com.xgc.common.vo.TreeNode;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class EntityService extends BaseService {

    private Entity dao = new Entity().dao();

    @Override
    public Model<?> getDao() {
        return dao;
    }

    /**
     * 查询物品关系树
     * @param treeNodeId
     * @return
     */
    public Collection<TreeNode> getEntityTree(String treeNodeId) {
        List<Record> list = null;
        String sql = "";
        if (StrKit.notBlank(treeNodeId)) {
            sql = Db.getSql("erp.getEntityTree");
            list = Db.find(sql, treeNodeId);
        } else {
            sql = Db.getSql("erp.getEntityRootTree");
            list = Db.find(sql);
        }
        Collection<TreeNode> nodes = new ArrayList<TreeNode>();
        for (int i = 0; i < list.size(); i++) {
            Record record = list.get(i);
            TreeNode node = new TreeNode();

            node.setId(record.getStr("entity_id"));
            node.setPid(record.getStr("par_entity"));
            node.setText(record.getStr("entity_name"));

            Collection<TreeNode> children = this.getEntityTree( record.getStr("entity_id"));
            node.setChildren(children);
            nodes.add(node);
        }
        return nodes;
    }

    public boolean saveEntity(Entity entity){
        return entity.save();
    }

    public Record getParentEntity(Integer entityId){
        String sql = Db.getSql("erp.getParentEntity");
        return Db.findFirst(sql,entityId);
    }

}
